import axios from 'axios'
import { formatFileTime } from './utils'
import { useUserStore } from '@/stores/user'
import { useSystemStore } from '@/stores/system'
function dataURLtoBlob(dataurl) {
  const bstr = atob(dataurl)
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: 'image/png' })
}
function blobToFile(theBlob, fileName) {
  theBlob.lastModifiedDate = new Date()
  theBlob.name = fileName
  return theBlob
}
export async function upload(base64, moduleName = 'weight') {
  const userStore = useUserStore()
  const systemStore = useSystemStore()
  const key = `${import.meta.env.MODE}/all_in_one/${moduleName}/${formatFileTime(new Date())}.${
    userStore.user.companyId
  }.${userStore.user.operateId}.jpg`
  const file = blobToFile(dataURLtoBlob(base64), key)
  const payload = {
    policy: systemStore.aliOssSignature.policy,
    OSSAccessKeyId: systemStore.aliOssSignature.OSSAccessKeyId,
    signature: systemStore.aliOssSignature.signature,
    success_action_status: 200,
    key,
    file
  }
  const formData = new FormData()
  for (const key in payload) {
    formData.append(key, payload[key])
  }
  const { VITE_BUCKET_NAME, VITE_OSS_REGION } = import.meta.env
  await axios.post(`https://${VITE_BUCKET_NAME}.${VITE_OSS_REGION}.aliyuncs.com/`, formData, {
    headers: {
      'Content-Type': 'application/octet-stream'
    }
  })
  return key
}
